package cn.wen.javax.net.mail.base;

import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.HtmlEmail;
import org.apache.log4j.Logger;

/**
 * Title：邮件发送器工厂。
 * <p>
 * Description：由静态方法创建。
 * <p>
 * Copyright：Copyright (c) 2010-2012
 * 
 * @author <a href="mailto:ct_wen@qq.com">ctwen</a>, 温承瑭
 * @version Revision：1.0 Date：2012/8/2 Description：初完成。
 *          <p>
 */
public class MailFactory {

    private static final Logger log = Logger.getLogger(MailFactory.class);

    public static HtmlEmail getSender(String domainName, String userName, String password) {
	return getSender("smtp." + domainName, domainName, userName, password);
    }

    public static HtmlEmail getSender(String hostName, String domainName, String userName, String password) {
	return getBaseSender(hostName, domainName, userName, password);
    }

    private static HtmlEmail getBaseSender(String hostName, String domainName, String userName, String password) {
	if (null == hostName && null == domainName) throw new IllegalArgumentException("主机名为空的时候，域名不能为空。");
	if (null == userName || null == password) throw new IllegalArgumentException("用户名或密码不能为空。");
	
	HtmlEmail mail = new HtmlEmail();

	mail.setHostName(hostName);
	mail.setSmtpPort(25);
	mail.setAuthentication(userName, password);
	mail.setCharset("UTF-8");

	if (null == domainName) return mail;

	try {
	    mail.setFrom(userName + "@" + domainName, userName);
	}
	catch (EmailException e) {
	    log.error(e.getMessage(), e);
	}

	return mail;
    }

}
